<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container" style="padding-bottom: 50px">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <!-- <px-button style="margin-top: 0" type="primary">抄表任务</px-button> -->
      <span>
        <px-form-item label="日期">
          <px-date-picker v-model="queryParams.queryDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">查询</px-button>
        <!-- <px-button style="margin-top: -17px" type="primary" plain @click="printFile()">打印</px-button> -->
        <px-button v-has="'WATER_METER_READING_EXPORT'" type="primary" style="margin-top: -17px" plain @click="handleExport">导出报表</px-button>
        <px-button v-has="'WATER_METER_READING_IMPORT'" type="primary" style="margin-top: -17px" plain @click="handleImport">导入</px-button>
      </span>
      <span v-if="submitStatus == '未提交'" style="float: right">未提交</span>
      <span v-else style="float: right">提交时间：{{ submitTime }}</span>
      <!-- <px-button style="margin-top: 0" type="primary" plain @click="exportToExcel()">导出</px-button> -->
    </px-form>
    <px-table
      v-if="!addVisible && !detailVisible"
      v-loading="loading"
      class="readingtable"
      :span-method="arraySpanMethod"
      :data="typeList"
      height="calc(100vh - 234px)"
      show-overflow-tooltip
      border
      :cell-style="cellStyle"
    >
      <!-- <px-table-column label="序号" align="center" prop="id" /> -->
      <px-table-column label="系统" prop="name">
        <template #default="scope">
          <span>{{ scope.row.systemName }}</span>
        </template>
      </px-table-column>

      <px-table-column label="水量名称" prop="name">
        <template #default="scope">
          <span style="color: #3b82f6; cursor: pointer" @click="spcshow(scope.row.spcJob)">{{ scope.row.name }}</span>
        </template>
      </px-table-column>

      <px-table-column label="仪表编号" width="160" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.meterName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="SPEC值" prop="specValue">
        <template #default="scope">
          <span>{{ scope.row.specValue }}</span>
        </template>
      </px-table-column>
      <px-table-column label="单位" width="160" prop="meterName">
        <template #default="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </px-table-column>
      <px-table-column label="计算水量" width="180" prop="calculateValue">
        <template #default="scope">
          <span v-if="scope.row.dataSource == '自动计算'">
            <px-input
              v-if="scope.row.edittable2"
              v-model="scope.row.calculateValue"
              style="width: calc(100% - 30px) !important"
              size="small"
              placeholder="请输入水量值"
              @blur="handelEdithiden2(scope.$index, 'modifyValue2')"
            />
            <span v-else class="modifyValue" @click="handelEdit2(scope.$index, 'modifyValue2')">
              <span v-if="scope.row.dataSource == '自动抄表'" class="modifyValue valueColor1" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
              <span v-if="scope.row.dataSource == '手动录入'" class="modifyValue valueColor2" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
              <span v-if="scope.row.dataSource == '自动计算'" class="modifyValue valueColor3" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
            </span>
          </span>
          <span v-else>
            <span class="modifyValue">
              <span v-if="scope.row.dataSource == '自动抄表'" class="modifyValue valueColor1" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
              <span v-if="scope.row.dataSource == '手动录入'" class="modifyValue valueColor2" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
              <span v-if="scope.row.dataSource == '自动计算'" class="modifyValue valueColor3" style="cursor: pointer">{{
                scope.row.calculateValue
              }}</span>
            </span>
          </span>
          <px-button link type="primary" @click="handleDetail2(scope.row.pointNumber)">
            <px-tooltip class="box-item" content="历史记录" placement="top">
              <px-icon><Time /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>

      <!-- <px-table-column label="自动采集数值（累计）" prop="readingValue">
        <template #default="scope">
          <span v-if="scope.row.dataSource == '自动抄表'" class="valueColor1">{{ scope.row.readingValue }}</span>
          <span v-if="scope.row.dataSource == '手动录入'" class="valueColor2">{{ scope.row.readingValue }}</span>
          <span v-if="scope.row.dataSource == '自动计算'" class="valueColor3">{{ scope.row.readingValue }}</span>
        </template>
      </px-table-column> -->
      <px-table-column label="抄表数值(累计)" prop="modifyValue">
        <template #default="scope">
          <span v-if="scope.row.dataSource != '自动计算'">
            <px-input
              v-if="scope.row.edittable"
              v-model="scope.row.mergedReadingValue"
              style="width: calc(100% - 30px) !important"
              size="small"
              placeholder="请输入抄表数值"
              @blur="handelEdithiden(scope.$index, 'modifyValue')"
            />
            <span v-else class="modifyValue" @click="handelEdit(scope.$index, 'modifyValue')">
              <!-- <span v-if="scope.row.mergedReadingValue > scope.row.readingValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.mergedReadingValue < scope.row.readingValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.mergedReadingValue == scope.row.readingValue" class="modifyValue" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span> -->
              <span v-if="scope.row.dataSource == '自动抄表'" class="modifyValue valueColor1" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.dataSource == '手动录入'" class="modifyValue valueColor2" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.dataSource == '自动计算'" class="modifyValue valueColor3" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
            </span>
          </span>
          <span v-else>
            <span class="modifyValue">
              <!-- <span v-if="scope.row.mergedReadingValue > scope.row.readingValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.mergedReadingValue < scope.row.readingValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.mergedReadingValue == scope.row.readingValue" class="modifyValue" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span> -->
              <span v-if="scope.row.dataSource == '自动抄表'" class="modifyValue valueColor1" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.dataSource == '手动录入'" class="modifyValue valueColor2" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
              <span v-if="scope.row.dataSource == '自动计算'" class="modifyValue valueColor3" style="cursor: pointer">{{
                scope.row.mergedReadingValue
              }}</span>
            </span>
          </span>
          <px-button link type="primary" @click="handleDetail(scope.row.pointNumber)">
            <px-tooltip class="box-item" content="历史记录" placement="top">
              <px-icon><Time /></px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <px-table-column label="计算公式" prop="readingTime">
        <template #default="scope">
          <span>{{ scope.row.formulaDesc ? scope.row.formulaDesc : "-" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="计算方式" prop="dataSource">
        <template #default="scope">
          <span v-if="scope.row.dataSource == '自动抄表'" class="valueColor1">自动抄表</span>
          <span v-if="scope.row.dataSource == '手动录入'" class="valueColor2">手动录入</span>
          <span v-if="scope.row.dataSource == '自动计算'" class="valueColor3">自动计算</span>
        </template>
      </px-table-column>
      <px-table-column label="数据采集时间" prop="readingTime">
        <template #default="scope">
          <span>{{ scope.row.readingTime }}</span>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <!-- spc窗口 -->
    <px-dialog v-model="innerVisible" draggable clickHideContent width="1372" title="SPC指标" append-to-body align-center>
      <px-form style="position: relative" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
        <px-radio-group v-model="timePeriod" style="position: absolute; top: 0; margin-left: 24px" @change="setTimePeriod()">
          <px-radio-button label="minutes">分钟</px-radio-button>
          <px-radio-button label="hour">小时</px-radio-button>
          <px-radio-button label="day">天</px-radio-button>
          <px-radio-button label="week">周</px-radio-button>
          <px-radio-button label="months">月</px-radio-button>
        </px-radio-group>
        <px-form-item label="时间日期" style="margin-left: 302px">
          <px-date-picker
            v-model="dateSpc"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :shortcuts="shortcuts"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleSpcAnalysis(detailjobId)">搜索</px-button>
        <px-button style="margin-top: -17px" icon="" @click="resetQuery2">重置</px-button>
      </px-form>
      <div class="spcchart">
        <chartsSearch
          :name="equipdata.indicatorName"
          :startValue="equipdata.startValue"
          :step="equipdata.step"
          :usl="equipdata.uslValue"
          :ucl="equipdata.uclValue"
          :uwl="equipdata.uwlValue"
          :target="equipdata.targetValue"
          :lwl="equipdata.lwlValue"
          :lcl="equipdata.lclValue"
          :lsl="equipdata.lslValue"
          :SpcAnalysis="SpcAnalysis"
          :pointUnit="pointUnit"
          :width="'1293px'"
          :height="'270px'"
        />
      </div>
      <div class="detailmain2">
        <px-tabs v-model="activeName" class="equipment-tabs">
          <px-tab-pane name="all">
            <template #label>
              <p class="pane-bottom">ALARM({{ totalCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>

          <px-tab-pane name="ooc">
            <template #label>
              <p class="pane-bottom">OOC({{ totalOocCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
          <px-tab-pane name="oow">
            <template #label>
              <p class="pane-bottom">OOW({{ totalOowCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
          <px-tab-pane name="oos">
            <template #label>
              <p class="pane-bottom">OOS({{ totalOosCount }})</p>
              <p class="pane-line" />
            </template>
          </px-tab-pane>
        </px-tabs>
      </div>
      <div style="padding: 20px 24px; background: white">
        <Alarm :activeName="activeName" :jobIdList="[detailjobId]" :dateSpc="dateSpc" />
      </div>
    </px-dialog>
    <px-dialog v-model="historyVisible" draggable clickHideContent width="1372" :title="historyTitle" append-to-body align-center>
      <px-table
        v-loading="loading"
        :cell-style="cellStyle2"
        :data="ModifyHistoryList"
        height="calc(100vh - 339px)"
        show-overflow-tooltip
        highlight-current-row
        border
      >
        <px-table-column label="系统" prop="systemName">
          <template #default="scope">
            <span>{{ scope.row.systemName }}</span>
          </template>
        </px-table-column>
        <px-table-column label="抄表项目" prop="gasType">
          <template #default="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </px-table-column>
        <px-table-column label="仪表" prop="value">
          <template #default="scope">
            <span>{{ scope.row.meterName }}</span>
          </template>
        </px-table-column>
        <px-table-column label="提交时间" prop="readingTime">
          <template #default="scope">
            <span>{{ scope.row.readingTime }}</span>
          </template>
        </px-table-column>
        <px-table-column v-if="historyTitle == '修正历史记录'" label="抄表值" prop="readingValue">
          <template #default="scope">
            <span>{{ scope.row.readingValue }}</span>
          </template>
        </px-table-column>
        <px-table-column v-if="historyTitle == '水量历史记录'" label="计算水量" prop="readingValue">
          <template #default="scope">
            <span>{{ scope.row.autoCalculateValue }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正值" prop="modifyValue">
          <template #default="scope">
            <span v-if="scope.row.modifyValue > scope.row.readingValue" class="modifyValue" style="color: #ef4444; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue < scope.row.readingValue" class="modifyValue" style="color: #10b981; cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
            <span v-if="scope.row.modifyValue == scope.row.readingValue" class="modifyValue" v style="cursor: pointer">{{
              scope.row.modifyValue
            }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正时间" prop="updateTime">
          <template #default="scope">
            <span>{{ scope.row.updateTime }}</span>
          </template>
        </px-table-column>
        <px-table-column label="修正人" prop="updater">
          <template #default="scope">
            <span>{{ scope.row.updater }}</span>
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>

      <pagination
        v-model:page="queryParams2.pageNum"
        v-model:limit="queryParams2.pageSize"
        style="margin-bottom: -10px"
        :total="total2"
        @pagination="getRukuList"
      />
    </px-dialog>
    <div v-has="'WATER_METER_READING_PUSH'" class="px-dialog-footer">
      <px-button type="primary" @click="tableReading()">提交</px-button>
      <!-- <px-button type="primary" @click="equipopenDetailsubmitForm()">提交</px-button> -->
    </div>
    <px-dialog v-model="dialogVisible" draggable clickHideContent title="导入数据" :width="600" :before-close="handelClose">
      <div class="import-bottle">
        <div class="import-bottle-upload">
          <div class="import-bottle-title">
            上传前请先
            <!-- <span class="download" @click="downloadFn"> 下载模板 </span> -->
            <span class="download" @click="handleExport"> 下载模板 </span>
            ，填写完成后导入数据
          </div>
          <importFiles
            ref="dialogSuccess"
            v-model="importFile"
            :upfileid="queryParams.queryDate"
            :isNotImmediateUpload="false"
            :uploadApi="balanceimportData"
            @submit="submitHandler"
          />
        </div>
      </div>
    </px-dialog>
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";

import {
  balancequeryReadingList,
  balanceupdateReading,
  balanceaddSubmitHistory,
  queryStatisticsModifyHistory,
  queryReadingModifyHistory,
  balancequeryReadingSubmitStatus,
  balanceimportData
} from "@/api/waterBalance";
import printJS from "print-js";
import * as XLSX from "xlsx/xlsx.mjs";
import chartsSearch from "../components/chartsSearch.vue";
import Alarm from "../components/alarm.vue";
import { spcquerySpcAnalysis, spcIndicatorquerySpcAnalysisResultList } from "@/api/spc";
import html2canvas from "html2canvas";
import importFiles from "./importFiles.vue";
const totalCount = ref("");
const totalOocCount = ref("");
const totalOosCount = ref("");
const totalOowCount = ref("");
const historyTitle = ref("");
const timePeriod = ref("minutes");
const tableElement = ref(null);
const imageUrl = ref(null);
const dialogVisible = ref(false);
const handleImport = () => {
  dialogVisible.value = true;
};
const submitHandler = val => {
  console.log(val);
  PxMessage({
    message: "数据导入成功",
    type: "success"
  });
  getList();
};
const printFile = () => {
  console.log(tableElement.value);
  if (tableElement.value) {
    html2canvas(document.getElementById("print-content"))
      .then(canvas => {
        imageUrl.value = canvas.toDataURL("image/png");
        setTimeout(() => {
          printJS({
            printable: "print-img",
            type: "html",
            style: `
         @media print{
          body,html{
            margin:0;
            padding:0;
            width:100%;
            height:100%;
            overflow:visible;
            position:reactive;
          }
          #print-img {
            transform-origin:top left;
            transform:scale(0.62);
          }
          img.print-full-page{
            position:absolute;
            top:0;
            left:0;
            width:100%;
            height:100%;
            object-fit:cover;
            page-break-before:always;
            page-break-after:always;
          }
         @page {margin: 1cm;}
          }
          `, // 去掉页眉页脚
            scanStyles: false,
            // targetStyles: ['*'],
            header: null,
            documentTitle: "水课抄表"
          });
        }, 100);
      })
      .catch(error => {
        console.log("Error", error);
      });
  }
};
const exportToExcel = () => {
  // 创建一个工作簿
  const wb = XLSX.utils.book_new();

  // 转换json到工作表
  let wsData = [
    ["系统", "抄表项目", "仪表", "提交时间", "抄表值", "修正值"],
    ...typeList.value.map(item => [item.systemName, item.name, item.meterName, item.readingTime, item.readingValue, item.modifyValue])
  ];
  const ws = XLSX.utils.json_to_sheet(wsData);

  // 添加工作表到工作簿
  XLSX.utils.book_append_sheet(wb, ws, "Sheet1");

  // 生成excel文件的blob对象
  const wbout = XLSX.write(wb, { bookType: "xlsx", type: "binary" });

  // 创建一个临时的a标签用于下载
  const blob = new Blob([s2ab(wbout)], { type: "application/octet-stream" });

  // 创建一个指向文件的URL
  const url = window.URL.createObjectURL(blob);

  // 创建一个a标签并模拟点击进行下载
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", "水课抄表.xlsx");
  document.body.appendChild(link);
  link.click();

  // 清理工作
  window.URL.revokeObjectURL(url);
  document.body.removeChild(link);

  // 字符串转ArrayBuffer
  function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
      view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
  }
};

const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const shortcuts = [
  {
    text: "本日",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "近7天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
      return [start, end];
    }
  },
  {
    text: "近30天",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
      return [start, end];
    }
  },
  {
    text: "本月",
    value: () => {
      const end = new Date();
      const start = new Date();
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  },
  {
    text: "本季度",
    value: () => {
      const end = new Date();
      const start = new Date();
      let currenMonth = start.getMonth();
      let quarter = Math.floor((currenMonth + 3) / 3) - 1;
      start.setMonth(quarter * 3, 1);
      start.setDate(1);
      start.setHours(0, 0, 0, 0);
      start.setTime(start.getTime());
      return [start, end];
    }
  }
];
onMounted(() => {
  if (localStorage.getItem("chukuList")) {
  }
});

const tableReading = () => {
  let celllist = typeList.value.filter(item2 => {
    let found = oldList.value.find(item1 => item1.readingId === item2.readingId);
    return !found || found.mergedReadingValue !== item2.mergedReadingValue;
  });
  let celllist2 = typeList.value.filter(item4 => {
    let found2 = oldList2.value.find(item2 => item2.statisticsId === item4.statisticsId);
    return !found2 || found2.calculateValue !== item4.calculateValue;
  });
  let historyList = celllist.map(item => {
    return {
      readingId: item.readingId,
      readingModifyValue: item.mergedReadingValue
    };
  });
  let historyList2 = celllist2.map(item => {
    return {
      statisticsId: item.statisticsId,
      statisticsModifyValue: item.calculateValue
    };
  });
  console.log(historyList);

  balanceupdateReading({
    readingList: historyList.filter(item => item.readingId != null),
    statisticsList: historyList2,
    queryDate: queryParams.value.queryDate,
    updateUserName: `${JSON.parse(localStorage.getItem("userInfo")).username}-${JSON.parse(localStorage.getItem("userInfo")).realName}`
  }).then((response: any) => {
    PxMessage({
      message: "抄表修正成功",
      type: "success"
    });

    getList();
  });
};
const { VITE_FANRUAN_BASE_URL, VITE_SERVE_API_STATIC_URL } = import.meta.env;
function handleExport() {
  let Token = getToken().accessToken || "";
  if (queryParams.value.queryDate != "") {
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=water%252F%25E6%258A%2584%25E8%25A1%25A8%25E4%25BF%25AE%25E6%25AD%25A3.cpt&token=${Token}&queryDate=${queryParams.value.queryDate}&format=excel&extype=simple&type=TW&facCode=${localStorage.getItem("facCode") || ""}&apiHost=${VITE_SERVE_API_STATIC_URL}`;
    window.location.href = url;
  } else {
    PxMessage({
      message: "请选择时间后再导出",
      type: "error"
    });
  }
}
const { proxy }: any = getCurrentInstance();
const dateSpc = ref([]);
const typeList = ref([]);
const progressVisible = ref(false);
const equipopenDetail = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const addVisible = ref(false);
const detailVisible = ref(false);
const innerVisible = ref(false);
const historyVisible = ref(false);
const total = ref(0);
const total2 = ref(0);
const dateRange = ref([]);
const activeName = ref("all");
const detailjobId = ref("");
// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: {},
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  wasteUnitoptions: [
    {
      value: "克",
      label: "克"
    },
    {
      value: "千克",
      label: "千克"
    },
    {
      value: "吨",
      label: "吨"
    }
  ],
  photoStatusFlag: false,
  fileStatusFlag: false,
  SpcAnalysis: [],
  equipdata: {
    id: "",
    jobId: "",
    indicatorName: "",
    classCode: "",
    systemCode: "",
    indicatorLevel: "",
    point: "",
    pointUnit: "",
    step: 0,
    startValue: 0,
    targetValue: 0,
    uclValue: 0,
    lclValue: 0,
    uwlValue: 0,
    lwlValue: 0,
    uslValue: 0,
    lslValue: 0,
    u3lValue: 0,
    l3lValue: 0
  },
  queryParams: {
    queryDate: new Date().toISOString().split("T")[0]
  },
  queryParams2: {
    orderByColumn: "",
    isAsc: "",
    emissionFactorName: "",
    factorSource: "",
    releaseYear: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    name: [{ required: true, message: "不能为空", trigger: "blur" }],
    serialNumber: [{ required: true, message: "不能为空", trigger: "blur" }],
    category: [{ required: true, message: "不能为空", trigger: "change" }],
    activityLevelUnit: [{ required: true, message: "不能为空", trigger: "change" }],
    emissionFactorName: [{ required: true, message: "不能为空", trigger: "blur" }],
    value: [{ required: true, message: "不能为空", trigger: "blur" }],
    factorSource: [{ required: true, message: "不能为空", trigger: "blur" }],
    releaseYear: [{ required: true, message: "不能为空", trigger: "blur" }],
    unit: [{ required: true, message: "不能为空", trigger: "blur" }],
    unitConversionRatio: [{ required: true, message: "不能为空", trigger: "blur" }],
    emissionCategory: [{ required: true, message: "不能为空", trigger: "change" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false,
  levelUnitList: [],
  energyList: [],
  categoryTypeList: [],
  SourceList: [],
  selectrow: null,
  nameSpanMap: {},
  oldList: [],
  oldList2: [],
  ModifyHistoryList: []
});
const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 6) {
    if (row.mergedReadingValue !== null) {
      if (row.readingModifyFlag != null) {
        return { background: "#FFDADA !important" };
      }
    }
  }
  if (columnIndex === 5) {
    if (row.calculateValue !== null) {
      if (row.calculateModifyFlag != null) {
        return { background: "#FFDADA !important" };
      }
      // if (row.mergedReadingValue < row.readingValue) {
      //   return { background: "#DFFFEA !important" };
      // }
      // if (row.mergedReadingValue == row.readingValue) {
      //   return {};
      // }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const cellStyle2 = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 5) {
    if (row.modifyValue !== null) {
      if (row.modifyValue > row.readingValue) {
        return { background: "#FFDADA !important" };
      }
      if (row.modifyValue < row.readingValue) {
        return { background: "#DFFFEA !important" };
      }
    }
  } else {
    return {};
  }
  // return { background: "#FFDADA" };
};
const {
  selectRukuList,
  queryParams,
  queryParams2,
  form,
  equipdata,
  rukuList,
  selectrow,
  nameSpanMap,
  oldList,
  oldList2,
  ModifyHistoryList,
  SpcAnalysis
} = toRefs(data);
const pointUnit = ref("空");
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  if (columnIndex === 0) {
    if (nameSpanMap.value[row.systemName] && rowIndex === nameSpanMap.value[row.systemName].rowIndex) {
      return {
        rowspan: nameSpanMap.value[row.systemName].rowspan,
        colspan: 1
      };
    } else {
      return {
        rowspan: 0,
        colspan: 0
      };
    }
  }
};

const getqueryCategoryList = () => {
  // queryChildByTypeCodeAndItemValue({
  //   value: "EMISSION_FACTOR_SOURCE",
  //   typeCode: "BICARBON"
  // }).then((response: any) => {
  //   SourceList.value = response;
  // });
};

const setTimePeriod = () => {
  handleSpcAnalysis(detailjobId.value);
};

const spcshow = async val => {
  innerVisible.value = true;
  //console.log(equipdata);
  detailjobId.value = val;
  const end = new Date();
  const start = new Date();
  start.setHours(0, 0, 0, 0);
  start.setTime(start.getTime());
  dateSpc.value = [formatDate(start), formatDate(end)];
  console.log(dateSpc.value);
  handleSpcAnalysis(val);
};
const handleSpcAnalysis = spcjob => {
  spcquerySpcAnalysis({
    jobIdList: [spcjob],
    // jobIdList: ["WATER_BAL_R_UPW0010_1"],
    timePeriod: timePeriod.value,
    startTime: dateSpc.value[0],
    endTime: dateSpc.value[1]
  }).then((response: any) => {
    SpcAnalysis.value = response;
  });
  spcIndicatorquerySpcAnalysisResultList({
    pageNum: queryParams2.value.pageNum,
    pageSize: queryParams2.value.pageSize,
    jobIdList: [detailjobId.value],
    alarmType: "",
    startTime: dateSpc.value[0],
    endTime: dateSpc.value[1]
  }).then(res => {
    if (res != null) {
      totalCount.value = res.totalCount;
      totalOocCount.value = res.totalOocCount;
      totalOosCount.value = res.totalOosCount;
      totalOowCount.value = res.totalOowCount;
    } else {
      totalCount.value = 0;
      totalOocCount.value = 0;
      totalOosCount.value = 0;
      totalOowCount.value = 0;
    }
  });
};

function formatDate(date) {
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
}
getqueryCategoryList();
function getRukuList() {
  loading.value = true;

  emissionFactorquery(queryParams2.value).then((response: any) => {
    rukuList.value = response.data;
    total2.value = response.total;
    loading.value = false;
  });
}

const handelEdit = (index, propName) => {
  typeList.value[index].edittable = true;
};
const handelEdithiden = (index, propName) => {
  // typeList.value[index].edittable = false;
  typeList.value.forEach(item => {
    item.edittable = false;
  });
};
const handelEdit2 = (index, propName) => {
  typeList.value[index].edittable2 = true;
};
const handelEdithiden2 = (index, propName) => {
  // typeList.value[index].edittable = false;
  typeList.value.forEach(item => {
    item.edittable2 = false;
  });
};
const submitStatus = ref("未提交");
const submitTime = ref("");
function getList() {
  loading.value = true;
  balancequeryReadingSubmitStatus({
    queryDate: queryParams.value.queryDate
  }).then(res => {
    console.log(res);
    submitStatus.value = res.submitStatus;
    submitTime.value = res.submitTime;
  });
  balancequeryReadingList(queryParams.value).then((response: any) => {
    nameSpanMap.value = {};
    let currentSpan = 0;
    if (response == null) {
      typeList.value = [];
      loading.value = false;
      return;
    }
    if (response != null && response.length > 0) {
      response.forEach((row, index) => {
        if (index === 0 || response[index - 1].systemName !== row.systemName) {
          currentSpan = 1;
          nameSpanMap.value[row.systemName] = {
            rowIndex: index,
            rowspan: 1
          };
        } else {
          currentSpan++;
          nameSpanMap.value[row.systemName].rowspan = currentSpan;
        }
      });
    }
    oldList.value = JSON.parse(JSON.stringify(response));
    oldList2.value = JSON.parse(JSON.stringify(response));
    typeList.value = response;
    oldList.value.map(item => ((item.edittable = false), (item.edittable2 = false)));
    oldList2.value.map(item => ((item.edittable = false), (item.edittable2 = false)));
    typeList.value.map(item => ((item.edittable = false), (item.edittable2 = false)));
    // typeList.value = response;
    loading.value = false;
  });
}

/** 取消按钮 */

/** 表单重置 */

/** 搜索按钮操作 */
function handleQuery(type) {
  getList();
}
function handleQuery2(type) {
  if (type == "search") {
    queryParams2.value.pageNum = 1;
  }
  getRukuList();
}

function resetQuery2() {
  queryParams2.value = {
    pageNum: queryParams2.value.pageNum,
    pageSize: queryParams2.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    dictWasteCode: "",
    startTime: "",
    endTime: "",
    status: "",
    orderBy: "",
    excludeInboundNumber: []
  };
  dateRange.value = [];
  handleQuery2("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  equipdata.value = {
    name: "",
    serialNumber: "",
    category: "",
    relatedEnergy: "",
    emissionFactorId: "",
    emissionFactorName: "",
    unit: "",
    factorSource: "",
    activityLevelUnit: "",
    unitConversionRatio: null,
    emissionCategory: "",
    standardValueList: [],
    createByName: "",
    updateByName: ""
  };
}
const handleDetail = async val => {
  historyVisible.value = true;
  const data = await queryReadingModifyHistory({ pointNumber: val, readingDate: queryParams.value.queryDate });
  console.log(data);
  historyTitle.value = "修正历史记录";
  ModifyHistoryList.value = data.historyDTO;
  // equipdata.value = data;
};
const handleDetail2 = async val => {
  historyVisible.value = true;
  const data = await queryStatisticsModifyHistory({ pointNumber: val, readingDate: queryParams.value.queryDate });
  console.log(data);
  historyTitle.value = "水量历史记录";
  ModifyHistoryList.value = data.historyDTO;
  // equipdata.value = data;
};

/** 提交按钮 */

const equipopenDetailsubmitForm = () => {
  balanceaddSubmitHistory({
    reportName: "抄表记录",
    reportDate: queryParams.value.queryDate
  }).then(res => {
    PxMessage({
      message: "提交成功",
      type: "success"
    });
  });
};
getList();
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table .cell) {
  line-height: 30px;
  vertical-align: middle;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 14px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.modifyValue {
  display: inline-block;
  width: calc(100% - 30px);
}

.valueColor1 {
  color: #3b82f6;
}

.valueColor2 {
  color: #f59e0b;
}

.valueColor3 {
  color: #10b981;
}

#print-content {
  position: absolute;
  left: -20000px;
}

#print-img {
  position: absolute;
  left: -20000px;
  width: 800px;
}

.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
      cursor: pointer;
    }
  }

  .import-bottle-upload {
    width: 100%;
    margin-bottom: 24px;
  }
}
</style>
